﻿using LeSoft.Application.Bussiness;
using LeSoft.Application.Cache;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LeSoft.Application.Web.Areas.BaseManage.Controllers
{
    public class WorkerController : MvcControllerBase
    {
        private WorkerBLL workerBLL = new WorkerBLL();
        private OrganizeBLL organizeBLL = new OrganizeBLL();
        private DepartmentBLL departmentBLL = new DepartmentBLL();
        private OrganizeCache organizeCache = new OrganizeCache();
        private DepartmentCache departmentCache = new DepartmentCache();
        private UserCache userCache = new UserCache();
        private PostBLL postBLL = new PostBLL();
        private RoleBLL roleBLL = new RoleBLL();
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Form()
        {
            return View();
        }

        #region 查询数据
        [HttpGet]
        public ActionResult GetListHtml(string keyword)
        {
            string retStr = string.Empty;
            DataTable dt = workerBLL.GetTable(keyword);
            if (dt != null && dt.Rows.Count > 0)
            {
                retStr = "<tbody>";
                foreach (DataRow dr in dt.Rows)
                {
                    retStr += "<tr><td class='client-avatar'><img src='../../Content/img/a2.jpg' /> </td>";
                    retStr += "<td><a data-toggle='tab' href='#' class='client-link'>" + dr["Name"].ToString() + "</a></td>";
                    retStr += "<td> " + dr["FullName"].ToString() + "</td> ";
                    retStr += "<td> " + dr["DutyName"].ToString() + "</td> ";
                    retStr += "<td> 工号:" + dr["Code"].ToString() + "</td> ";
                    retStr += !string.IsNullOrEmpty(dr["PhoneNum"].ToString()) ? "<td class='contact-type'><i class='fa fa-phone'> </i></td><td>" + dr["PhoneNum"].ToString() + "</td>" : !string.IsNullOrEmpty(dr["TelPhoneNum"].ToString()) ? "<td class='contact-type'><i class='fa fa-phone'> </i></td><td>" + dr["TelPhoneNum"].ToString() + "</td>" : !string.IsNullOrEmpty(dr["Email"].ToString()) ? " <td class='contact-type'><i class='fa fa-envelope'> </i></td><td>" + dr["Email"].ToString() + "</td>" : "<td class='contact-type'></td><td></td>";
                    retStr += " <td class='client-actions text-center'><button class='btn btn-info btn-sm' onclick=btn_detail(\'" + dr["Id"].ToString() + "\')><i class='fa fa-eye'></i> 详情 </button><span>&nbsp;</span><button class='btn btn-warning btn-sm' onclick=btn_edit(\'" + dr["Id"].ToString() + "\')><i class='fa fa-pencil'></i> 编辑 </button><span>&nbsp;</span><button class='btn btn-danger btn-sm' onclick=btn_delete(\'" + dr["Id"].ToString() + "\')><i class='fa fa-trash-o'></i> 删除 <button></td></tr>";
                }
                retStr = retStr + "</tobdy><tfoot><tr><td colspan='7'> <ul class='pagination pull-right'></ul></td></tr></tfoot>";
            }
            else
            {
                retStr = "<tbody><tr><td>没有员工数据</td></tr></tbody>";
            }
            var JsonData = new
            {
                html = retStr,
                firstId = dt.Rows.Count > 0 ? dt.Rows[0]["Id"].ToString() : "",
                count = dt.Rows.Count
            };
            return Content(JsonData.ToJson());
        }

        [HttpGet]
        public ActionResult GetDetailHtml(string keyword)
        {
            string retStr = string.Empty;
            var obj = workerBLL.GetEntity(keyword);
            var organizeName = obj != null && !string.IsNullOrEmpty(obj.OrganizeId) ? organizeBLL.GetEntity(obj.OrganizeId).FullName : "";
            var departmentName = obj != null && !string.IsNullOrEmpty(obj.DepartmentId) ? departmentBLL.GetEntity(obj.DepartmentId).FullName : "";
            var postname = obj != null && !string.IsNullOrEmpty(obj.PostId) ? postBLL.GetEntity(obj.PostId).FullName : "";
            var rolename = obj != null && !string.IsNullOrEmpty(obj.RoleId) ? roleBLL.GetEntity(obj.RoleId).FullName : "";
            retStr += "<div class=row m-b-lg>";
            retStr = retStr + "<div class='col-lg-4 text-center'><h2>" + obj.Name.ToString() + "</h2><div class='m-b-sm'><img alt='image' class='img-circle' src='../../Content/img/a2.jpg' style='width: 62px'> </div></div>";
            retStr = retStr + "<div class='col-lg-8'><h3>个人详情</h3><p>姓名：" + obj.Name.ToString() + "</p><p>所属公司：" + organizeName + "</p><p>所属部门：" + departmentName + "</p><p>所属职位：" + obj.DutyName + "</p><p>所属岗位：" + postname + "</p><p>所属角色：" + rolename + "</p><br />";
            retStr = retStr + "<button type='button' class='btn btn-primary btn-sm btn-block'><i class='fa fa-envelope'></i> 发送消息</button></div>";
            retStr = retStr + "</div>";
            retStr = retStr + "<div class='client-detail'> <div class='full-height-scroll'> <strong>当前动态</strong>";
            retStr = retStr + "<ul class='list-group clear-list'><li class='list-group-item fist-item'> <span class='pull-right'> 09:00</span> 请联系我 </li><li class='list-group-item'><span class='pull-right'> 10:16 </span> 签合同 </li><li class='list-group-item'><span class='pull-right'> 08:22 </span> 开新公司</li> <li class='list-group-item'> <span class='pull-right'> 11:06 </span> 打电话给李四  </li>   </ul>" +
                    "<strong>备注</strong>  <p>40亿影帝黄渤先生明明可以靠脸吃饭，可是他却偏偏靠才华，唱歌居然也这么好听！</p>" +
                    "</div> </div>";
            var jsonData = new
            {
                html = retStr
            };
            return Content(jsonData.ToJson());

        }

        [HttpGet]
        public ActionResult GetFormJson(string keyValue)
        {
            var data = workerBLL.GetEntity(keyValue);
            return Content(data.ToJson());
        }
        /// <summary>
        /// 员工列表
        /// </summary>
        /// <param name="pagination">分页参数</param>
        /// <param name="queryJson">查询参数</param>
        /// <returns>返回分页列表Json</returns>
        [HttpGet]
        public ActionResult GetPageListJson(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            var data = workerBLL.GetPageList(pagination, queryJson);
            if (!OperatorProvider.Provider.Current().IsSystem)
            {
                var organizeids = organizeCache.GetSonOrganizeId(OperatorProvider.Provider.Current().CompanyId);
                //data = data.Where(t => t.OrganizeId == OperatorProvider.Provider.Current().CompanyId).ToList();
            }
            if (!string.IsNullOrEmpty(queryJson))
            {
                var queryParam = queryJson.ToJObject();
                if (!queryParam["organizeId"].IsEmpty())
                {
                    string OrganizeId = new Cache.OrganizeCache().GetSonOrganizeId(queryParam["organizeId"].ToString());
                    queryParam["organizeId"] = OrganizeId;
                }
                queryJson = queryParam.ToJson();
            }
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }



        public ActionResult GetBussinessPageList(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            var data = workerBLL.GetBussinessWorker(pagination, queryJson);         
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }
        /// <summary>
        /// 员工列表
        /// </summary>
        /// <param name="departmentId">部门Id</param>
        /// <returns>返回用户列表Json</returns>
        [HttpGet]
        public ActionResult GetListJson(string departmentId)
        {
            var data = new UserCache().GetList(departmentId);
            return Content(data.ToJson());
        }
        /// <summary>
        /// 组织机构+部门树
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetTreeJson()
        {
            var organizedata = organizeCache.GetList();
            if (!OperatorProvider.Provider.Current().IsSystem)
            {
                var entity = organizeBLL.GetEntity(OperatorProvider.Provider.Current().CompanyId);
                organizedata = organizedata.Where(t => t.OrganizeId == entity.OrganizeId || t.OrganizeId == entity.ParentId).ToList();
            }
            var departmentdata = departmentCache.GetList();
            var treeList = new List<TreeEntity>();
            foreach (OrganizeEntity item in organizedata)
            {
                #region 机构
                TreeEntity tree = new TreeEntity();
                bool hasChildren = organizedata.Count(t => t.ParentId == item.OrganizeId) == 0 ? false : true;
                if (hasChildren == false)
                {
                    hasChildren = departmentdata.Count(t => t.OrganizeId == item.OrganizeId) == 0 ? false : true;
                    if (hasChildren == false)
                    {
                        continue;
                    }
                }
                tree.id = item.OrganizeId;
                tree.text = item.FullName;
                tree.value = item.OrganizeId;
                tree.parentId = item.ParentId;
                tree.img = "fa fa-sitemap";
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.Attribute = "Sort";
                tree.AttributeValue = "Organize";
                treeList.Add(tree);
                #endregion
            }
            foreach (DepartmentEntity item in departmentdata)
            {
                #region 部门
                TreeEntity tree = new TreeEntity();
                tree.id = item.DepartmentId;
                tree.text = item.FullName;
                tree.value = item.DepartmentId;
                if (item.ParentId == "0")
                {
                    tree.parentId = item.OrganizeId;
                }
                else
                {
                    tree.parentId = item.ParentId;
                }
                tree.isexpand = true;
                tree.complete = true;
                tree.img = "fa fa-th-list";
                tree.hasChildren = true;
                tree.Attribute = "Sort";
                tree.AttributeValue = "Department";
                tree.AttributeA = "OrganizeId";
                tree.AttributeValueA = item.OrganizeId;
                treeList.Add(tree);
                #endregion
            }
            return Content(treeList.TreeToJson());
        }

        /// <summary>
        /// 部门
        /// </summary>
        /// <param name="organizeid"></param>
        /// <returns></returns>
        public ActionResult GetWorkerTreeJson(string organizeid)
        {
            var departmentdata = departmentCache.GetList();
            if (!OperatorProvider.Provider.Current().IsSystem) departmentdata = departmentdata.Where(t => t.OrganizeId == organizeid);
            var treeList = new List<TreeEntity>();
            foreach (DepartmentEntity item in departmentdata)
            {
                #region 部门
                TreeEntity tree = new TreeEntity();
                tree.id = item.DepartmentId;
                tree.text = item.FullName;
                tree.value = item.DepartmentId;
                tree.parentId = item.ParentId;
                tree.isexpand = true;
                tree.complete = true;
                tree.img = "fa fa-th-list";
                tree.hasChildren = true;
                tree.Attribute = "Sort";
                tree.AttributeValue = "Department";
                tree.AttributeA = "OrganizeId";
                tree.AttributeValueA = item.OrganizeId;
                treeList.Add(tree);
                #endregion
            }
            return Content(treeList.TreeToJson());
        }


        /// <summary>
        /// 部门+员工
        /// </summary>
        /// <param name="organizeid"></param>
        /// <returns></returns>
        public ActionResult GetDptWorkerTreeJson(string organizeid)
        {

            var departmentdata = departmentCache.GetList();
            if (!string.IsNullOrEmpty(organizeid)) departmentdata = departmentdata.Where(t => t.OrganizeId == organizeid);
            var workerdata = workerBLL.GetList().Where(t => t.OrganizeId == organizeid);
            var treeList = new List<TreeEntity>();
            foreach (DepartmentEntity item in departmentdata)
            {
                #region 部门
                TreeEntity tree = new TreeEntity();
                tree.id = item.DepartmentId;
                tree.text = item.FullName;
                tree.value = item.DepartmentId;
                tree.parentId = item.ParentId;
                tree.isexpand = false;
                tree.complete = true;
                tree.img = "fa fa-th-list";
                tree.hasChildren = true;
                tree.Attribute = "Sort";
                tree.AttributeValue = "Department";
                tree.AttributeA = "OrganizeId";
                tree.AttributeValueA = item.OrganizeId;
                treeList.Add(tree);
                #endregion
            }
            foreach (WorkerEntity item in workerdata)
            {
                #region 员工
                TreeEntity tree = new TreeEntity();
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Id;
                tree.parentId = item.DepartmentId;
                tree.isexpand = false;
                tree.complete = true;
                tree.img = "fa fa-th-list";
                tree.hasChildren = true;
                tree.Attribute = "Sort";
                tree.AttributeValue = "Worker";
                tree.AttributeA = "OrganizeId";
                tree.AttributeValueA = item.OrganizeId;
                treeList.Add(tree);
                #endregion
            }
            return Content(treeList.TreeToJson());
        }
        #endregion

        #region 验证数据
        [HttpGet]
        public ActionResult ExistCode(string Code, string keyValue)
        {
            bool IsOk = workerBLL.ExistEnCode(Code, keyValue);
            return Content(IsOk.ToString());
        }
        #endregion
        #region 提交数据
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult SaveForm(string keyValue, string strWorkerEntity, string FormInstanceId, string strModuleFormInstanceEntity)
        {
            WorkerEntity workerEntity = strWorkerEntity.ToObject<WorkerEntity>();
            string objectId = workerBLL.SaveForm(keyValue, workerEntity);
            return Success("操作成功。");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult RemoveForm(string keyValue)
        {
            workerBLL.RemoveForm(keyValue);
            return Success("删除成功。");
        }
        #endregion
    }
}
